package cn.yunyichina.provider.register.listener;

import cn.yunyichina.provider.framework.data.SpringContextHandler;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.provider.iface.entity.pay.notify.UnifiedPayNotifyMessage;
import cn.yunyichina.provider.register.service.impl.PayServiceImpl;
import cn.yunyichina.utils.commons.DateUtils;
import cn.yunyichina.utils.convert.JsonUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.listener.MessageListener;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 监听挂号支付成功后的kafka消息
 */
public class RegAliPayMessageListener implements MessageListener<Integer, String> {

    private Logger logger = LoggerFactory.getLogger(RegAliPayMessageListener.class);

    @Autowired
    private static PayServiceImpl payService;

    public void onMessage(ConsumerRecord<Integer, String> integerStringConsumerRecord) {
        String jsonString = integerStringConsumerRecord.value();
        logger.info("RegAliPayMessageListener.onMessage.jsonString -> {}", jsonString);
        try {
            UnifiedPayNotifyMessage notifyMessage = JsonUtils.parseObject(jsonString, UnifiedPayNotifyMessage.class);
            String orderNo = notifyMessage.getOrderNo();
            String openId = notifyMessage.getOpenId();
            String appId = notifyMessage.getAppId();
//            Float payAmount = Float.parseFloat((String) jsonObject.get("total_amount")) * 100;
            BigDecimal payAmount = new BigDecimal(notifyMessage.getTotalAmount());//jsonObject.getBigDecimal("total_amount").multiply(new BigDecimal(100));
            String tradeNo = notifyMessage.getTradeNo();

            Map<String, Object> dataMap = new HashMap<String, Object>();

            dataMap.put("yyt_order_no", orderNo);
            dataMap.put("pay_time", notifyMessage.getPayTime());
            dataMap.put("open_id", openId);
            dataMap.put("payee_app_id", appId);
            if(notifyMessage.getMchData() != null && StringUtils.isNotBlank(notifyMessage.getMchData().getPayMode())){
                dataMap.put("pay_mode", notifyMessage.getMchData().getPayMode());
            }else {
                dataMap.put("pay_mode", "22");
            }
            dataMap.put("pay_amount", payAmount.intValue());
            dataMap.put("payment_deal_id", tradeNo);
            dataMap.put("insurance_amount", notifyMessage.getInsuranceAmount());
            dataMap.put("pay_amount", notifyMessage.getPayAmount());

            String industry_sepc_detail = (String) notifyMessage.getMedicalContent();
            String tempStr = null;
            if(StringUtils.isNotBlank(industry_sepc_detail)) {
                try {
                    // 因为支付宝传入进来的参数中含有"{、}"、"[、]"等这些字符，所以要进行替换才能进行JSON解析
                    tempStr = industry_sepc_detail.replace("\"{", "{");
                    tempStr = tempStr.replace("}\"", "}");
                    tempStr = tempStr.replace("\"[", "[");
                    tempStr = tempStr.replace("]\"", "]");
                } catch (Exception e) {
//                addOrderToExceptionList(order);
                    e.printStackTrace();
                    logger.error("RegAliPayMessageListener,解析回调出错", e);
                }
            }

            JSONObject extendParams = new JSONObject();
            extendParams.put("industry_sepc_detail",tempStr);
            dataMap.put("extendParams", extendParams);

            if(payService == null){
                payService = SpringContextHandler.getBean(PayServiceImpl.class);
            }
            Response response = payService.ackPayRegRecord( JsonUtils.toJsonString(dataMap),"");
            logger.info("onMessage 挂号写单返回 response:{}", JSON.toJSONString(response));

        } catch (Exception e) {
            logger.error("onMessage error.", e);
        }

        logger.info("onMessage end.");
    }

    public static void main(String a[]){
        String industry_sepc_detail = "{\"registration_order_pay\":{\"brlx\":\"1\",\"mzghdj\":\"[{\"je\":6,\"jssj\":\"2017-04-21 11:30:23\",\"zfxm\":\"02\"},{\"je\":6,\"jssj\":\"2017-04-21 11:30:23\",\"zfxm\":\"0201\"},{\"je\":6,\"jssj\":\"2017-04-21 11:30:23\",\"zfxm\":\"03\"},{\"je\":529.17,\"jssj\":\"2017-04-21 11:30:23\",\"zfxm\":\"0303\"},{\"je\":523.17,\"jssj\":\"2017-04-21 11:30:23\",\"zfxm\":\"0306\"}]\",\"cblx\":\"1\",\"cbmonth\":\"\"}}";
        String tempStr = null;
        try {
            // 因为支付宝传入进来的参数中含有"{、}"、"[、]"等这些字符，所以要进行替换才能进行JSON解析
            tempStr = industry_sepc_detail.replace("\"{", "{");
            tempStr = tempStr.replace("}\"", "}");
            tempStr = tempStr.replace("\"[", "[");
            tempStr = tempStr.replace("]\"", "]");
        } catch (Exception e) {
//                addOrderToExceptionList(order);

            throw e;
        }
        Map<String, Object> industryMap = JsonUtils.parseObject(tempStr,Map.class);
        Map<String,Object> registrationOrderPay = (Map<String, Object>) industryMap.get("registration_order_pay");
        System.out.println(tempStr);
        System.out.println(registrationOrderPay);
        System.out.println(registrationOrderPay.get("brlx"));
    }
}
